package com.dts.server;

import java.io.*;
import java.net.Socket;
import java.util.Map;

public class ClientHandler implements Runnable {
    private final Socket clientSocket;
    private BufferedReader in;
    private PrintWriter out;
    public ClientHandler(Socket socket) {
        this.clientSocket = socket;
    }
    public void send(String mesage) {
        out.println(mesage);
    }

    @Override
    public void run() {
        try {
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            out = new PrintWriter(clientSocket.getOutputStream(), true);
            notice("有人上线");
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                if ("bye".equalsIgnoreCase(inputLine)) {
                    break;
                }
                broadcast(inputLine); // 广播消息
            }
        } catch (IOException e) {
            System.err.println("客户端：" + clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort() + "退出了");
        } finally {
            closeConnection();
        }
    }

    private void notice(String type) {
        String users = "";
        for (String s : Server.clientMap.keySet()) {
            users =  users + "[" + s + "] ";
        }
        for (ClientHandler client : Server.clientMap.values()) {
            client.send(type + "，在线用户：" + users);
        }
    }

    private void broadcast(String message) {
        String trimStr = message.trim();
        String[] s = trimStr.split(" ");
        try {
            if (s[0].contains(":") && s.length > 1) {
                String user = s[0];
                String msg = trimStr.substring(trimStr.indexOf(" ")).trim();
                ClientHandler client = Server.clientMap.get(user);
                if(client != null){
                    client.send(clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort() + "的消息:" + msg);
                }
            } else {
                message = clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort() + "的消息:" + message;
                for (Map.Entry<String, ClientHandler> entry : Server.clientMap.entrySet()) {
                    ClientHandler handler = entry.getValue();
                    handler.send(message);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void closeConnection() {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if (out != null) {
            out.close();
        }
        if (clientSocket != null) {
            try {
                clientSocket.close();
            } catch (IOException e) {
                System.err.println("关闭客户端连接失败: " + e.getMessage());
            }
        }
        Server.clientMap.remove(clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort());
        notice("有人下线");
    }

}
